﻿var mainViewModel = new MainViewModel();

function MainViewModel() {
    var selfMain = this;

    selfMain.CurrentPage = ko.observable();
    selfMain.FirstLoad = ko.observable(true);
    selfMain.PageNotFound = ko.observable();
    selfMain.TryIndexed = ko.observable(false);
    selfMain.IndexedId = ko.observable();

    selfMain.Hashes = [];
    selfMain.Hashes.NotFound = "NotFound";

    selfMain.ChangeHash = function (hash) {
        window.location.hash = '#' + hash;
    }

    selfMain.ChangePage = function (page) {
        $.when(health.MainExit()).done(function () {
            document.location = page;
        });
    }

    selfMain.IsValidModel = function (model) {
        for (var property in model) {
            if (model[property].hasError)
                if (model[property].hasError())
                    return false;
        }
        return true;
    };

    ko.extenders.email = function (target, check) {
        target.hasError = ko.observable();

        function validateEmail(emailAddress) {
            target.hasError(!whoever.EmailIsValid(emailAddress));
        };
        validateEmail(target());
        target.subscribe(validateEmail);

        return target;
    };

    ko.extenders.emailRequired = function (target, check) {
        target.hasError = ko.observable();

        function validateEmail(emailAddress) {
            target.hasError(!whoever.EmailIsValid(emailAddress) || whoever.IsEmpty(emailAddress));
        };
        validateEmail(target());
        target.subscribe(validateEmail);

        return target;
    };

    ko.extenders.accountOrEmail = function (target, check) {
        target.hasError = ko.observable();

        function validate(value) {
            if (value)
                if (value.indexOf('@') != -1)
                    target.hasError(!whoever.EmailIsValid(value));
                else
                    target.hasError(whoever.IsEmpty(value));
            else
                target.hasError(true);
        }
        validate(target());
        target.subscribe(validate);

        return target;
    };

    ko.extenders.regExpValidate = function (target, params) {
        target.validationMessage = ko.observable();
        if (params.mask() && params.mask() != "") {
            target.hasError = ko.observable(true);
        }
        else {
            target.hasError = ko.observable(false);
        }

        validate(target());

        target.subscribe(validate);

        return target;

        function validate(newValue) {
            if (params.mask() && params.mask() != "") {
                var regExp = new RegExp(params.mask());
                target.hasError(regExp.test(newValue) ? false : true);
            }
            else {
                target.hasError(false);
            }
        }
    };

    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBinding, viewModel, context) {
            var observable = valueAccessor();
            var value = ko.utils.unwrapObservable(valueAccessor());

            $(element).val(health.Date(value));
            $(element).attr("value", health.Date(value));

            $(element).datepicker({
                viewMode: 0,
            })
            .on('changeDate', function (eval) {
                var newValue = new Date(eval.date)
                observable(newValue);

                $(element).datepicker("hide");
            });
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            $(element).val(health.Date(value));
            $(element).attr("value", health.Date(value));
        }
    };

    Sammy(function () {
        this.get('#:hash/:id', function () {
            var hash = this.params.hash;
            var id = this.params.id;

            var indexedHash = hash + "/" + id;

            if (selfMain.Hashes.indexOf(hash) == -1)
                hash = selfMain.Hashes.NotFound;

            if (!selfMain.FirstLoad()) {
                $.when(health.MainExit()).done(function () {
                    health.MainEnter();
                    selfMain.ChangeHash(indexedHash);
                    selfMain.CurrentPage(hash);
                });
            }
            else {
                selfMain.FirstLoad(false);
                health.MainInit();
                health.MainEnter();
                selfMain.ChangeHash(indexedHash);
                selfMain.CurrentPage(hash);
            }

            whoever.EnableAll();

            selfMain.TryIndexed(true);
            selfMain.IndexedId(id);
        });
        this.get('#:hash', function () {
            var hash = this.params.hash;

            if (selfMain.Hashes.indexOf(hash) == -1)
                hash = selfMain.Hashes.NotFound;

            if (!selfMain.FirstLoad()) {
                $.when(health.MainExit()).done(function () {
                    health.MainEnter();
                    selfMain.ChangeHash(hash);
                    selfMain.CurrentPage(hash);
                });
            }
            else {
                selfMain.FirstLoad(false);
                health.MainInit();
                health.MainEnter();
                selfMain.ChangeHash(hash);
                selfMain.CurrentPage(hash);
            }

            whoever.EnableAll();

            selfMain.TryIndexed(false);
        });
        this.get('', function () {
            this.app.runRoute('get', '#' + selfMain.CurrentPage());
        });
    });
}

